package com.link.base.tencent.corpwx.addressbook.service;

import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.media.model.CorpWxMedia;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.corpwx.addressbook.model.User;
import com.link.base.tencent.corpwx.addressbook.util.UserUtil;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.media.util.MediaUtil;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 企业微信 - 用户服务 - API实现
 *
 * @author liying
 * @date 2019/2/21
 */
@Service
public class AddressBookUserServiceImpl extends BasicServiceImpl<User> implements AddressBookUserService {

    @Resource
    private AgentService agentService;

    @Override
    public String transformOpenId(String userId, int agentId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            throw new BasicServiceException("userId不能为空！");
        }
        if (StringUtils.isBlank(StringUtils.toString(agentId))) {
            throw new BasicServiceException("agentId不能为空！");
        }
        // 根据agentId获取access_token
        String accessToken = agentService.getExistAccessToken(StringUtils.toString(agentId));
        // userId 转 openId
        JSONObject obj = UserUtil.transformOpenId(accessToken, userId);

        return obj.getString("openid");
    }

    @Override
    public String batchUpdateUsers(List list, LinkedHashMap titleMap, String agentId,  Boolean totalFlag) throws Exception {
        LCLogger.info().withMessageKey("batchReplaceUsers").withMessage("开始异步更新企业微信通讯录").flush();
        // 根据提供的列表生成csv文件
        String outputPath = YmlConstants.getTemporaryIOFileDir() + "corpwx";
        File file = MediaUtil.createCSVFile(list, titleMap, outputPath);
        // 上传csv文件到服务器
        LCLogger.info().withMessageKey("batchReplaceUsers").withMessage("上传csv文件到微信服务器").flush();
        String accessToken = agentService.getExistAccessToken(agentId);
        CorpWxMedia corpWxMedia = MediaUtil.uploadMedia(accessToken, "file", file);
        if (corpWxMedia.getMediaId() == null) {
            throw new Exception("获取mediaId失败！");
        }
        LCLogger.info().withMessageKey("batchReplaceUsers").withMessage("获取到的mediaId：" + corpWxMedia.getMediaId()).flush();
        // 开始同步通讯录到企业微信
        LCLogger.info().withMessageKey("batchReplaceUsers").withMessage("开始同步通讯录到企业微信").flush();
        JSONObject resultObj;
        if (totalFlag) {
            resultObj = UserUtil.batchReplaceUser(accessToken, corpWxMedia.getMediaId(), false);
        } else {
            resultObj = UserUtil.batchSyncUser(accessToken, corpWxMedia.getMediaId(), false);
        }
        LCLogger.info().withMessageKey("batchReplaceUsers").withMessage("同步到通讯录结果，jobid：" + resultObj.getString("jobid") ).flush();
        return  resultObj.getString("jobid");
    }

    @Override
    public void deleteUserById(String userId, String agentId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            throw new BasicServiceException("userId不能为空！");
        }
        String accessToken = agentService.getExistAccessToken(agentId);
        UserUtil.deleteWxUser(accessToken, userId);
    }

    @Override
    public void addUser(User user, String agentId) throws Exception {
        String accessToken = agentService.getExistAccessToken(agentId);
        UserUtil.newWxUser(accessToken, user);
    }

    @Override
    public void updateUser(User user, String agentId) throws Exception {
        String accessToken = agentService.getExistAccessToken(agentId);
        UserUtil.updateWxUser(accessToken, user);
    }

    @Override
    public void synUser(User user, String agentId) throws Exception {
        String accessToken = agentService.getExistAccessToken(agentId);
        User result = UserUtil.queryWxUserById(accessToken,String.valueOf( user.getUserId()));
        if ( result != null) {
            UserUtil.updateWxUser(accessToken, user);
        } else {
            UserUtil.newWxUser(accessToken, user);
        }
    }
}
